
package com.kunminx.viabus.ui.adapter;

import com.kunminx.viabus.utils.ImageNetWork;
import com.kunminx.viabus.ResourceTable;
import com.kunminx.viabus.repertory.bean.NoteBean;
import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.*;

import java.util.List;

/*
* 相当于原来的 adaper 下的文件
*/
public class ListProvider extends BaseItemProvider {
    private final List<NoteBean> list;
    private final AbilitySlice slice;

    public ListProvider(List<NoteBean> mList, AbilitySlice mSlice) {
        this.list = mList;
        this.slice = mSlice;
    }


    /**
    * 获取 list count
    */
    @Override
    public int getCount() {
        return list == null ? 0 : list.size();
    }

    /**
     * 获取列表项
     * @param position 位置
     */
    @Override
    public Object getItem(int position) {
        if (list != null && position >= 0 && position < list.size()){
            return list.get(position);
        }
        return null;
    }

    /**
     * 获取列表项
     * @param position 位置
     */
    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * getComponent
     * @param position 位置
     * @param convertComponent 组件
     * @param componentContainer container
     */
    @Override
    public Component getComponent(int position, Component convertComponent, ComponentContainer componentContainer) {
        final Component cpt;
        SettingHolder holder;
        NoteBean sampleItem = list.get(position);
        if (convertComponent == null) {
            cpt = LayoutScatter.getInstance(slice).parse(ResourceTable.Layout_list_item, null, false);
            holder = new SettingHolder(cpt);
            // 将获取到的子组件信息绑定到列表项的实例中
            cpt.setTag(holder);
        } else {
            cpt = convertComponent;
            // 从缓存中获取到列表项实例后，直接使用绑定的子组件信息进行数据填充。
            holder = (SettingHolder) cpt.getTag();
        }
        // 获取图片 element
        Image img = (Image)cpt.findComponentById(ResourceTable.Id_iv_thumb);
        /// 将网络图片转未 PixelMap，并绘制(网上找的封装好的)——异步，会比较慢
        new ImageNetWork(slice,img,sampleItem.getImgUrl()).start();
        // holder.settingIma.setPixelMap(pixelMap);
        holder.settingText.setText(sampleItem.getTitle());
        return cpt;
    }

    // 用于保存列表项中的子组件信息
    public static class SettingHolder {
        // private Image settingIma;
        private final Text settingText;
        SettingHolder(Component component) {
            // settingIma = (Image) component.findComponentById(ResourceTable.Id_iv_thumb);
            settingText = (Text) component.findComponentById(ResourceTable.Id_tv_title);
        }
    }

}
